package com.sailors.common.task.provider.infra.system.config.task;

import com.alibaba.fastjson.JSONObject;
import com.yomahub.tlog.core.thread.TLogInheritableTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.concurrent.DelayQueue;

@Component
@Slf4j
public class DelayedFileTaskRunner implements InitializingBean {

    @Autowired
    @Qualifier("fileTaskDelayQueue")
    public DelayQueue<CommonDelayQueueTask<Long>> delayQueueTasks;

    @Override
    public void afterPropertiesSet() {
        // 从延时队列中获取元素
        TLogInheritableTask runnable = new TLogInheritableTask() {
            @Override
            public void runTask() {
                while (true) {
                    try {
                        log.info("开始等待队列获取数据！");
                        CommonDelayQueueTask<Long> commonDelayQueueTask = delayQueueTasks.take();
                        log.info("执行DelayedFileTask：{}", commonDelayQueueTask);
                        commonDelayQueueTask.getConsumer().accept(commonDelayQueueTask.getParam());
                    } catch (Exception e) {
                        log.warn("DelayedFileTaskRunner failed!");
                        log.warn(e.getMessage(), e);
                    }
                }
            }
        };
        new Thread(runnable).start();
        log.info("DelayedFileTaskRunner启动！");
    }
}
